package com.hyg.module_user.userInfo;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.method.DigitsKeyListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.bumptech.glide.Glide;
import com.hyg.lib_base.Net.NetworkUtils;
import com.hyg.lib_base.mainUtils.StatusBarUtil;
import com.hyg.lib_base.mainUtils.Utils;
import com.hyg.lib_common.Base.BaseActivity;
import com.hyg.lib_common.DataModel.personal.UserDetail;
import com.hyg.lib_common.DataUtil.UserSPUtils;
import com.hyg.lib_common.constant.UrlUtils;
import com.hyg.lib_common.constant.Constants;
import com.hyg.lib_common.sweetalertdialog.SweetAlertDialog;
import com.hyg.module_user.R;
import com.hyg.module_user.databinding.ActivityUpdateUserInfoBinding;
import com.lljjcoder.Interface.OnCityItemClickListener;
import com.lljjcoder.bean.CityBean;
import com.lljjcoder.bean.DistrictBean;
import com.lljjcoder.bean.ProvinceBean;
import com.lljjcoder.citywheel.CityConfig;
import com.lljjcoder.style.citylist.Toast.ToastUtils;
import com.lljjcoder.style.citypickerview.CityPickerView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.FormBody;


@Route(path = Constants.PATH_ACTIVITY_MODULE_USER_SETTING_UPDATE)
/**更新用户信息页面*/
public class UpdateUserInfoActivity extends BaseActivity {
    private String UserInfoId = "", userId = "", realName = "", gender = "", idNumber = "", socialId = "", address = "", marryInfo = "",
            historyInfo = "", operationInfo = "", allergyInfo = "", familyInfo = "", tasteInfo = "", headImage = "", createTime = "", updateTime = "";

    private String midnumber = "(^\\d{15}$)|(^\\d{17}[0-9Xx]$)";//正则表达式:验证身份证
    private String mrealname = "^[\u4e00-\u9fa5]{2,4}$";// 验证汉字(1-4个汉字)
    private String mphone = "^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$";//验证手机号
    //    private String msocialId = "(^\\d{15}$)|(^\\d{16}$)|(^\\d{17}$)|(^\\d{17}[0-9Xx]$)|(^\\d{18}$)|(^\\d{19}$)";//正则表达式:验证身份证
    private TimePickerView pvTime;

    private CityPickerView mPicker = new CityPickerView();

    private static final int REQUEST_PICK = 101;

    ActivityUpdateUserInfoBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityUpdateUserInfoBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        init();
    }

    public void init() {
        initView();
        initData();
    }


    public void initView() {
        StatusBarUtil.setStatusBar(1, this, getResources().getColor(R.color.white), 00, null, null, true);
        binding.back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
                overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);
            }
        });
        binding.saveMsg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                setSave();
            }
        });

        binding.rlName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UpdateName();
            }
        });

        binding.rlSex.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UpdateSex();
            }
        });

        binding.rlIdcard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UpdateIdNumber();
            }
        });

        UpdateSocialId();
        binding.rlBirthday.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pvTime.show(binding.rlBirthday);
            }
        });

        binding.rlAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectAddress();
            }
        });

        binding.rlMarryInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UpdateMarryInfo();
            }
        });


        binding.rlHistoryInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UpdateHistoryInfo();
            }
        });


        binding.rlOperationInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UpdateOperationInfo();
            }
        });


        binding.rlAllergyInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UpdateAllergyInfo();
            }
        });


        binding.rlFamilyInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UpdateFamilyInfo();
            }
        });


        binding.rlTasteInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UpdateTasteInfo();
            }
        });

        binding.rlUpdateHead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UpdataHeadImage();
            }
        });
    }


    public void initData() {
        queryUserInfo();
        mPicker.init(this);//城市选择器 数据预加载
    }

    private MyHandler myHandler = new MyHandler(this);

    private static class MyHandler extends Handler {
        private final WeakReference<Context> reference;
        private UpdateUserInfoActivity activity;

        public MyHandler(Context context) {
            reference = new WeakReference<>(context);
            activity = (UpdateUserInfoActivity) reference.get();
        }

        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1://个人信息保存
                    try {
                        JSONObject jsondata = new JSONObject(msg.obj.toString());//获取返回的JSONObject原对象
                        String status = URLDecoder.decode(jsondata.getString("code"), "utf-8");
                        String message = URLDecoder.decode(jsondata.getString("message"), "utf-8");
//                        Log.d("welcomeadUUM", jsondata + "");
                        if (status.equals("200")) {
                            if (activity.pDialog.isShowing())
                                activity.pDialog.dismiss();
                            activity.pDialog = new SweetAlertDialog(activity, SweetAlertDialog.SUCCESS_TYPE);
                            //        pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
                            activity.pDialog.setTitleText("个人信息保存成功");
                            activity.pDialog.setConfirmButton("OK", new SweetAlertDialog.OnSweetClickListener() {
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismiss();
//                                    UpdateUserMessage.this.finish();
//                                    overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);
                                }
                            });
//                            pDialog.setCancelable(false);
                            activity.pDialog.show();
                            activity.myHandler.sendEmptyMessageDelayed(101, 600);
                        } else {
                            activity.ErrorDialog(message);
                        }
                    } catch (JSONException e) {
                        Log.d(CrashTAG, "" + e.getMessage());
                    } catch (UnsupportedEncodingException e) {
                        Log.d(CrashTAG, "" + e.getMessage());
                    }
                    break;
                case 101:
                    if (activity.pDialog.isShowing()) {
                        activity.pDialog.dismiss();
                    }
                    break;
            }
        }
    }

    ;


    //进入个人信息页面时，先向数据库查询个人信息，判断显示控件信息
    public void queryUserInfo() {
        UserDetail userInfo = UserSPUtils.getUserDetail(UpdateUserInfoActivity.this);
        if (userInfo == null) return;


        UserInfoId = userInfo.getId() + "";
        userId = userInfo.getUserId() + "";
        realName = userInfo.getRealName()+ "";
        gender = userInfo.getGender()+ "";
        idNumber = userInfo.getIdNumber()+ "";
        socialId = userInfo.getSocialId()+ "";
        address = userInfo.getAddress()+ "";
        marryInfo = userInfo.getMarryInfo()+ "";
        historyInfo = userInfo.getHistoryInfo()+ "";
        operationInfo = userInfo.getOperationInfo()+ "";
        allergyInfo = userInfo.getAllergyInfo()+ "";
        familyInfo = userInfo.getFamilyInfo()+ "";
        tasteInfo = userInfo.getTasteInfo()+ "";
        headImage = userInfo.getHeadIcon()+ "";
        if (!TextUtils.isEmpty(headImage)) {
            Glide.with(this).load(headImage).error(R.mipmap.headimg).into(binding.ivHeadPortrait);
        }
        if (!Utils.isEmpty(realName)) {
            binding.llRealname.setVisibility(View.VISIBLE);
            binding.btRealname.setVisibility(View.GONE);
            binding.etRealname.setText(realName);
        }
        if (!Utils.isEmpty(gender)) {
            binding.llSex.setVisibility(View.VISIBLE);
            binding.btSex.setVisibility(View.GONE);
            if (gender.equals("1")) {
                binding.etSex.setText("男");
            } else if (gender.equals("2")) {
                binding.etSex.setText("女");
            } else {
                binding.etSex.setText(gender);
            }
        }
        if (!Utils.isEmpty(idNumber)) {
            binding.llIdnumber.setVisibility(View.VISIBLE);
            binding.btIdNumber.setVisibility(View.GONE);
            binding.etIdNumber.setText(idNumber.substring(0, 3) + "******");
        }
        if (!Utils.isEmpty(socialId)) {
            binding.llSocialId.setVisibility(View.VISIBLE);
            binding.btSocialId.setVisibility(View.GONE);
//                et_socialId.setText(socialId.substring(0,3)+"***********"+socialId.substring(14));
            binding.etSocialId.setText(socialId);
        }
        if (!Utils.isEmpty(address)) {
            binding.llAddr.setVisibility(View.VISIBLE);
            binding.btAddress.setVisibility(View.GONE);
            binding.etAddr.setText(address);
        }
        if (!Utils.isEmpty(marryInfo)) {
            binding.llMarryInfo.setVisibility(View.VISIBLE);
            binding.btMarryInfo.setVisibility(View.GONE);
            binding.etMarryInfo.setText(marryInfo);
        }
        if (!Utils.isEmpty(historyInfo)) {
            binding.llHistoryInfo.setVisibility(View.VISIBLE);
            binding.btHistoryInfo.setVisibility(View.GONE);
            binding.etHistoryInfo.setText(historyInfo);
        }
        if (!Utils.isEmpty(operationInfo)) {
            binding.llOperationInfo.setVisibility(View.VISIBLE);
            binding.btOperationInfo.setVisibility(View.GONE);
            binding.etOperationInfo.setText(operationInfo);
        }
        if (!Utils.isEmpty(allergyInfo)) {
            binding.llAllergyInfo.setVisibility(View.VISIBLE);
            binding.btAllergyInfo.setVisibility(View.GONE);
            binding.etAllergyInfo.setText(allergyInfo);
        }
        if (!Utils.isEmpty(familyInfo)) {
            binding.llFamilyInfo.setVisibility(View.VISIBLE);
            binding.btFamilyInfo.setVisibility(View.GONE);
            binding.etFamilyInfo.setText(familyInfo);
        }
        if (!Utils.isEmpty(tasteInfo)) {
            binding.llTasteInfo.setVisibility(View.VISIBLE);
            binding.btTasteInfo.setVisibility(View.GONE);
            binding.etTasteInfo.setText(tasteInfo);
        }

    }

    public void setCompleteDialog(SweetAlertDialog sad) {
        sad.setTitleText("更换完成")
                .setContentText("退出页面时，请务必保存")
                .setConfirmText("好，知道啦")
                .setConfirmClickListener(null)
                .changeAlertType(SweetAlertDialog.SUCCESS_TYPE);
        final Timer timer = new Timer();
        TimerTask timerTask = new TimerTask() {
            public void run() {
                myHandler.sendEmptyMessage(101);
                timer.cancel();
            }
        };
        timer.schedule(timerTask, 1000);
    }

    //修改姓名
    public void UpdateName() {
        if (Utils.isFastClick()) return;
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.dialog_setname, null);
        view.setLayoutParams(lp);
        TextView tips = (TextView) view.findViewById(R.id.Tips_message);
        tips.setText("姓名格式为2-4位中文汉字");
        final EditText userInput = (EditText) view.findViewById(R.id.changename_edit);
        userInput.setHint("昵称 / 真名");
        if (pDialog.isShowing())
            pDialog.dismiss();
        pDialog = new SweetAlertDialog(this, SweetAlertDialog.CUSTOM_IMAGE_TYPE);
        //        pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
        pDialog.setTitleText("更换姓名");
        pDialog.setCustomView(view);    // 使用用户自定义的布局控件
        pDialog.setConfirmButton("确认更换", new SweetAlertDialog.OnSweetClickListener() {
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                if (!userInput.getText().toString().equals("")) {
                    if (!userInput.getText().toString().matches(mrealname)) {
                        //确认后切换对话框样式,新的dialog 显示内容和 效果
                        sweetAlertDialog.setTitleText("格式错误")
                                .setContentText("姓名为2-4位中文汉字，请重新输入。")
                                .setConfirmText("好，知道啦")
                                .setConfirmClickListener(null)
                                .changeAlertType(SweetAlertDialog.ERROR_TYPE);
                    } else {
                        realName = userInput.getText().toString();
                        binding.llRealname.setVisibility(View.VISIBLE);
                        binding.btRealname.setVisibility(View.GONE);
                        binding.etRealname.setText(realName);
                        setSave();
                    }
                } else {
                    sweetAlertDialog.setTitleText("格式错误")
                            .setContentText("姓名输入内容不可为空")
                            .setConfirmText("好，知道啦")
                            .setConfirmClickListener(null)
                            .changeAlertType(SweetAlertDialog.ERROR_TYPE);
                }
            }
        });
        //        pDialog.setCancelable(false); //设置对话框外不可点击，默认值为true可点击.
        pDialog.show();

    }

    //修改性别
    private String[] sexArry = new String[]{"保密", "女", "男"};// 性别选择


    public void UpdateSex() {
        if (Utils.isFastClick()) return;
        if (pDialog.isShowing())
            pDialog.dismiss();
        pDialog = new SweetAlertDialog(this, SweetAlertDialog.NORMAL_TYPE);
        //        pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
        pDialog.setTitleText("性别选择");
        pDialog.setConfirmButton("男性", new SweetAlertDialog.OnSweetClickListener() {
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                gender = "男";
                binding.llSex.setVisibility(View.VISIBLE);
                binding.btSex.setVisibility(View.GONE);
                binding.etSex.setText(gender);
                sweetAlertDialog.dismiss();
                setSave();
            }
        });
        pDialog.setCancelButton("女性", new SweetAlertDialog.OnSweetClickListener() {
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                gender = "女";
                binding.llSex.setVisibility(View.VISIBLE);
                binding.btSex.setVisibility(View.GONE);
                binding.etSex.setText(gender);
                sweetAlertDialog.dismiss();
                setSave();
            }
        });
        pDialog.show();
    }

    //修改身份证号
    public void UpdateIdNumber() {
        if (Utils.isFastClick()) return;
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.dialog_setname, null);
        view.setLayoutParams(lp);
        TextView tips = (TextView) view.findViewById(R.id.Tips_message);
        tips.setText("身份证号格式为15-18位");
        final EditText userInput = (EditText) view.findViewById(R.id.changename_edit);
        userInput.setHint("请输入身份证号");
        userInput.setKeyListener(DigitsKeyListener.getInstance("1234567890xX"));
        userInput.setMaxLines(1);
        userInput.setEllipsize(TextUtils.TruncateAt.END);
        userInput.setFilters(new InputFilter[]{new InputFilter.LengthFilter(18)});
        ;

        if (pDialog.isShowing())
            pDialog.dismiss();
        pDialog = new SweetAlertDialog(this, SweetAlertDialog.CUSTOM_IMAGE_TYPE);
        //        pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
        pDialog.setTitleText("身份证号");
        pDialog.setCustomView(view);    // 使用用户自定义的布局控件
        pDialog.setConfirmButton("确认", new SweetAlertDialog.OnSweetClickListener() {
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                if (!userInput.getText().toString().equals("")) {
                    if (!userInput.getText().toString().matches(midnumber)) {
                        //确认后切换对话框样式,新的dialog 显示内容和 效果
                        sweetAlertDialog.setTitleText("格式错误")
                                .setContentText("身份证号格式为15-18位，请重新输入。")
                                .setConfirmText("好，知道啦")
                                .setConfirmClickListener(null)
                                .changeAlertType(SweetAlertDialog.ERROR_TYPE);
                    } else {
                        idNumber = userInput.getText().toString();
                        binding.llIdnumber.setVisibility(View.VISIBLE);
                        binding.btIdNumber.setVisibility(View.GONE);
                        binding.etIdNumber.setText(idNumber.substring(0, 3) + "******");
                        setSave();
                    }
                } else {
                    sweetAlertDialog.setTitleText("格式错误")
                            .setContentText("输入内容不可为空")
                            .setConfirmText("好，知道啦")
                            .setConfirmClickListener(null)
                            .changeAlertType(SweetAlertDialog.ERROR_TYPE);
                }
            }
        });
        //        pDialog.setCancelable(false); //设置对话框外不可点击，默认值为true可点击.
        pDialog.show();

    }

    //修改社保号
    public void UpdateSocialId() {
//        if(Utils.isFastClick())return;
//        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
//        LayoutInflater inflater = LayoutInflater.from(this);
//        View view = inflater.inflate(R.layout.dialog_setname, null);
//        view.setLayoutParams(lp);
//        TextView tips = (TextView)view.findViewById(R.id.Tips_message);
//        tips.setText("社保号格式为15-19位数字");
//        final EditText userInput = (EditText) view.findViewById(R.id.changename_edit);
//        userInput.setInputType(InputType.TYPE_CLASS_NUMBER);
//        userInput.setHint("请输入社保号");
//
//        if (pDialog.isShowing())
//            pDialog.dismiss();
//        pDialog = new SweetAlertDialog(this, SweetAlertDialog.CUSTOM_IMAGE_TYPE);
//        //        pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
//        pDialog.setTitleText("社会保障卡号");
//        pDialog.setCustomView(view);    // 使用用户自定义的布局控件
//        pDialog.setConfirmButton("确认更新", new SweetAlertDialog.OnSweetClickListener() {
//            public void onClick(SweetAlertDialog sweetAlertDialog) {
//                if (!userInput.getText().toString().equals("")) {
//                    if (!userInput.getText().toString().matches(msocialId)) {
//                        //确认后切换对话框样式,新的dialog 显示内容和 效果
//                        sweetAlertDialog.setTitleText("格式错误")
//                                .setContentText("社保号格式为15-19位数字，请重新输入。")
//                                .setConfirmText("好，知道啦")
//                                .setConfirmClickListener(null)
//                                .changeAlertType(SweetAlertDialog.ERROR_TYPE);
//                    } else {
//                        socialId = userInput.getText().toString();
//                        ll_socialId.setVisibility(View.VISIBLE);
//                        bt_socialId.setVisibility(View.GONE);
//                        et_socialId.setText(socialId);
//                        setSave();
//                    }
//                } else {
//                    sweetAlertDialog.setTitleText("格式错误")
//                            .setContentText("输入内容不可为空")
//                            .setConfirmText("好，知道啦")
//                            .setConfirmClickListener(null)
//                            .changeAlertType(SweetAlertDialog.ERROR_TYPE);
//                }
//            }
//        });
//        //        pDialog.setCancelable(false); //设置对话框外不可点击，默认值为true可点击.
//        pDialog.show();


        //控制时间范围(如果不设置范围，则使用默认时间1900-2100年，此段代码可注释)
        //因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
        Calendar selectedDate = Calendar.getInstance();
        if (!Utils.isEmpty(socialId)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                Date birthdayDate = sdf.parse(socialId);       //将Date类型转换成String类型
                selectedDate.setTime(birthdayDate);
            } catch (ParseException e) {
                Log.d("birthday", "生日格式不对");
//                e.printStackTrace();
            }
        }
        Calendar startDate = Calendar.getInstance();
        startDate.set(1920, 0, 1);
        Calendar endDate = Calendar.getInstance();
        int year = endDate.get(Calendar.YEAR);
        int month = endDate.get(Calendar.MONTH);
        int date = endDate.get(Calendar.DATE);
        endDate.set(year, month, date);
        //时间选择器
        pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                // 这里回调过来的v,就是show()方法里面所添加的 View 参数，如果show的时候没有添加参数，v则为null
//                TextView btn = (TextView) v;
//                btn.setText(getTimes(date));
//                socialId = btn.getText().toString();
                socialId = getTimes(date).toString();
                binding.llSocialId.setVisibility(View.VISIBLE);
                binding.btSocialId.setVisibility(View.GONE);
                binding.etSocialId.setText(socialId);
                setSave();
            }
        })
                .setType(new boolean[]{true, true, true, false, false, false})//年月日时分秒 的显示与否，不设置则默认全部显示
                .setLabel("年", "月", "日", "时", "分", "秒")
                .isCenterLabel(true)
                .setDividerColor(Color.DKGRAY)
                //                .setContentSize(21)
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setDecorView(null)
                .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                .isDialog(true)//是否显示为对话框样式
                .build();

    }

    private String getTimes(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    //修改婚育史
    public void UpdateMarryInfo() {
        if (Utils.isFastClick()) return;
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.dialog_setname, null);
        view.setLayoutParams(lp);
        TextView tips = (TextView) view.findViewById(R.id.Tips_message);
        tips.setText("您的婚育情况");
        final EditText userInput = (EditText) view.findViewById(R.id.changename_edit);
        userInput.setHint("输入不超过50个字数");
        userInput.setFilters(new InputFilter[]{new InputFilter.LengthFilter(50)});

        if (pDialog.isShowing())
            pDialog.dismiss();
        pDialog = new SweetAlertDialog(this, SweetAlertDialog.CUSTOM_IMAGE_TYPE);
        //        pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
        pDialog.setTitleText("婚育史");
        pDialog.setCustomView(view);    // 使用用户自定义的布局控件
        pDialog.setConfirmButton("确认更新", new SweetAlertDialog.OnSweetClickListener() {
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                if (!userInput.getText().toString().equals("")) {
                    marryInfo = userInput.getText().toString();
                    binding.llMarryInfo.setVisibility(View.VISIBLE);
                    binding.btMarryInfo.setVisibility(View.GONE);
                    binding.etMarryInfo.setText(marryInfo);
                    setSave();
                } else {
                    sweetAlertDialog.setTitleText("格式错误")
                            .setContentText("输入内容不可为空")
                            .setConfirmText("好，知道啦")
                            .setConfirmClickListener(null)
                            .changeAlertType(SweetAlertDialog.ERROR_TYPE);
                }
            }
        });
        //        pDialog.setCancelable(false); //设置对话框外不可点击，默认值为true可点击.
        pDialog.show();

    }

    //修改既往史
    public void UpdateHistoryInfo() {
        if (Utils.isFastClick()) return;
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.dialog_setname, null);
        view.setLayoutParams(lp);
        TextView tips = (TextView) view.findViewById(R.id.Tips_message);
        tips.setText("个人现在以及往期病史");
        final EditText userInput = (EditText) view.findViewById(R.id.changename_edit);
        userInput.setHint("输入不超过50个字数");
        userInput.setFilters(new InputFilter[]{new InputFilter.LengthFilter(50)});

        if (pDialog.isShowing())
            pDialog.dismiss();
        pDialog = new SweetAlertDialog(this, SweetAlertDialog.CUSTOM_IMAGE_TYPE);
        //        pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
        pDialog.setTitleText("既往史");
        pDialog.setCustomView(view);    // 使用用户自定义的布局控件
        pDialog.setConfirmButton("确认更新", new SweetAlertDialog.OnSweetClickListener() {
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                if (!userInput.getText().toString().equals("")) {
                    historyInfo = userInput.getText().toString();
                    binding.llHistoryInfo.setVisibility(View.VISIBLE);
                    binding.btHistoryInfo.setVisibility(View.GONE);
                    binding.etHistoryInfo.setText(historyInfo);
                    setSave();
                } else {
                    sweetAlertDialog.setTitleText("格式错误")
                            .setContentText("输入内容不可为空")
                            .setConfirmText("好，知道啦")
                            .setConfirmClickListener(null)
                            .changeAlertType(SweetAlertDialog.ERROR_TYPE);
                }
            }
        });
        //        pDialog.setCancelable(false); //设置对话框外不可点击，默认值为true可点击.
        pDialog.show();

    }

    //修改手术史
    public void UpdateOperationInfo() {
        if (Utils.isFastClick()) return;
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.dialog_setname, null);
        view.setLayoutParams(lp);
        TextView tips = (TextView) view.findViewById(R.id.Tips_message);
        tips.setText("个人现在以及往期手术史");
        final EditText userInput = (EditText) view.findViewById(R.id.changename_edit);
        userInput.setHint("输入不超过50个字数");
        userInput.setFilters(new InputFilter[]{new InputFilter.LengthFilter(50)});

        if (pDialog.isShowing())
            pDialog.dismiss();
        pDialog = new SweetAlertDialog(this, SweetAlertDialog.CUSTOM_IMAGE_TYPE);
        //        pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
        pDialog.setTitleText("手术史");
        pDialog.setCustomView(view);    // 使用用户自定义的布局控件
        pDialog.setConfirmButton("确认更新", new SweetAlertDialog.OnSweetClickListener() {
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                if (!userInput.getText().toString().equals("")) {
                    operationInfo = userInput.getText().toString();
                    binding.llOperationInfo.setVisibility(View.VISIBLE);
                    binding.btOperationInfo.setVisibility(View.GONE);
                    binding.etOperationInfo.setText(operationInfo);
                    setSave();
                } else {
                    sweetAlertDialog.setTitleText("格式错误")
                            .setContentText("输入内容不可为空")
                            .setConfirmText("好，知道啦")
                            .setConfirmClickListener(null)
                            .changeAlertType(SweetAlertDialog.ERROR_TYPE);
                }
            }
        });
        //        pDialog.setCancelable(false); //设置对话框外不可点击，默认值为true可点击.
        pDialog.show();

    }

    //修改过敏史
    public void UpdateAllergyInfo() {
        if (Utils.isFastClick()) return;
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.dialog_setname, null);
        view.setLayoutParams(lp);
        TextView tips = (TextView) view.findViewById(R.id.Tips_message);
        tips.setText("个人现在以及往期过敏史");
        final EditText userInput = (EditText) view.findViewById(R.id.changename_edit);
        userInput.setHint("输入不超过50个字数");
        userInput.setFilters(new InputFilter[]{new InputFilter.LengthFilter(50)});

        if (pDialog.isShowing())
            pDialog.dismiss();
        pDialog = new SweetAlertDialog(this, SweetAlertDialog.CUSTOM_IMAGE_TYPE);
        //        pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
        pDialog.setTitleText("过敏史");
        pDialog.setCustomView(view);    // 使用用户自定义的布局控件
        pDialog.setConfirmButton("确认更新", new SweetAlertDialog.OnSweetClickListener() {
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                if (!userInput.getText().toString().equals("")) {
                    allergyInfo = userInput.getText().toString();
                    binding.llAllergyInfo.setVisibility(View.VISIBLE);
                    binding.btAllergyInfo.setVisibility(View.GONE);
                    binding.etAllergyInfo.setText(allergyInfo);
                    setSave();
                } else {
                    sweetAlertDialog.setTitleText("格式错误")
                            .setContentText("输入内容不可为空")
                            .setConfirmText("好，知道啦")
                            .setConfirmClickListener(null)
                            .changeAlertType(SweetAlertDialog.ERROR_TYPE);
                }
            }
        });
        //        pDialog.setCancelable(false); //设置对话框外不可点击，默认值为true可点击.
        pDialog.show();

    }

    //修改家族史
    public void UpdateFamilyInfo() {
        if (Utils.isFastClick()) return;
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.dialog_setname, null);
        view.setLayoutParams(lp);
        TextView tips = (TextView) view.findViewById(R.id.Tips_message);
        tips.setText("直系家族遗传病史");
        final EditText userInput = (EditText) view.findViewById(R.id.changename_edit);
        userInput.setHint("输入不超过50个字数");
        userInput.setFilters(new InputFilter[]{new InputFilter.LengthFilter(50)});

        if (pDialog.isShowing())
            pDialog.dismiss();
        pDialog = new SweetAlertDialog(this, SweetAlertDialog.CUSTOM_IMAGE_TYPE);
        //        pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
        pDialog.setTitleText("家族史");
        pDialog.setCustomView(view);    // 使用用户自定义的布局控件
        pDialog.setConfirmButton("确认更新", new SweetAlertDialog.OnSweetClickListener() {
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                if (!userInput.getText().toString().equals("")) {
                    familyInfo = userInput.getText().toString();
                    binding.llFamilyInfo.setVisibility(View.VISIBLE);
                    binding.btFamilyInfo.setVisibility(View.GONE);
                    binding.etFamilyInfo.setText(familyInfo);
                    setSave();
                } else {
                    sweetAlertDialog.setTitleText("格式错误")
                            .setContentText("输入内容不可为空")
                            .setConfirmText("好，知道啦")
                            .setConfirmClickListener(null)
                            .changeAlertType(SweetAlertDialog.ERROR_TYPE);
                }
            }
        });
        //        pDialog.setCancelable(false); //设置对话框外不可点击，默认值为true可点击.
        pDialog.show();

    }

    //修改口味偏好
    public void UpdateTasteInfo() {
        if (Utils.isFastClick()) return;
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.dialog_setname, null);
        view.setLayoutParams(lp);
        TextView tips = (TextView) view.findViewById(R.id.Tips_message);
        tips.setText("个人现往的口味偏好");
        final EditText userInput = (EditText) view.findViewById(R.id.changename_edit);
        userInput.setHint("输入不超过50个字数");
        userInput.setFilters(new InputFilter[]{new InputFilter.LengthFilter(50)});

        if (pDialog.isShowing())
            pDialog.dismiss();
        pDialog = new SweetAlertDialog(this, SweetAlertDialog.CUSTOM_IMAGE_TYPE);
        //        pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
        pDialog.setTitleText("口味偏好");
        pDialog.setCustomView(view);    // 使用用户自定义的布局控件
        pDialog.setConfirmButton("确认更新", new SweetAlertDialog.OnSweetClickListener() {
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                if (!userInput.getText().toString().equals("")) {
                    tasteInfo = userInput.getText().toString();
                    binding.llTasteInfo.setVisibility(View.VISIBLE);
                    binding.btTasteInfo.setVisibility(View.GONE);
                    binding.etTasteInfo.setText(tasteInfo);
                    setSave();
                } else {
                    sweetAlertDialog.setTitleText("格式错误")
                            .setContentText("输入内容不可为空")
                            .setConfirmText("好，知道啦")
                            .setConfirmClickListener(null)
                            .changeAlertType(SweetAlertDialog.ERROR_TYPE);
                }
            }
        });
        //        pDialog.setCancelable(false); //设置对话框外不可点击，默认值为true可点击.
        pDialog.show();

    }

    //修改生日
    public void UpdateBirthday() {
        if (Utils.isFastClick()) return;
        Calendar calendar = Calendar.getInstance();
        View view = (LinearLayout) getLayoutInflater().inflate(R.layout.date_dialog, null);
        final DatePicker datePicker = (DatePicker) view.findViewById(R.id.date_picker);
        //设置日期简略显示 否则详细显示 包括:星期\周
        datePicker.setCalendarViewShown(false);
        //初始化当前日期
        calendar.setTimeInMillis(System.currentTimeMillis());
        datePicker.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH), null);

        new AlertDialog.Builder(UpdateUserInfoActivity.this, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT)
                .setTitle("修改生日")
                .setView(view)
                .setPositiveButton("确认修改", new DialogInterface.OnClickListener() {
                    @SuppressLint("DefaultLocale")
                    public void onClick(DialogInterface dialog,
                                        int arg1) {
                        StringBuffer sb = new StringBuffer();
                        sb.append(String.format("%d-%02d-%02d",
                                datePicker.getYear(),
                                datePicker.getMonth() + 1,
                                datePicker.getDayOfMonth()));
//                        et_birth.setText(sb);
                        editorn = sn.edit();
                        editorn.putString("birthday", sb.toString());
                        editorn.commit();
                    }
                })
                .setNegativeButton("取消", null)
                .show();

    }

    //修改地址
    //    public void UpdateAddress(){
    //        LayoutInflater layoutInflater = LayoutInflater.from(this);
    //        View addrView = layoutInflater.inflate(R.layout.dialog_setname, null);
    //        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
    //                this,AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
    //        alertDialogBuilder.setView(addrView);
    //        alertDialogBuilder.setTitle("更换地址");
    //        final EditText userInput = (EditText) addrView.findViewById(R.id.changename_edit);
    //        alertDialogBuilder
    //                .setCancelable(false)
    //                .setPositiveButton("确认更换",
    //                        new DialogInterface.OnClickListener() {
    //                            public void onClick(DialogInterface dialog, int id) {
    //                                // 获取edittext的内容,显示到textview
    //                                et_addr.setText(userInput.getText());
    //                            }
    //                        })
    //                .setNegativeButton("取消",
    //                        new DialogInterface.OnClickListener() {
    //                            public void onClick(DialogInterface dialog, int id) {
    //                                Dialog.dismiss();
    //                            }
    //                        });
    //        AlertDialog alertDialog = alertDialogBuilder.create();
    //        alertDialog.show();
    //    }

    //选择自己所在城市
    private void selectAddress() {
        if (Utils.isFastClick()) return;
        //        仿iOS滚轮样式的城市选择器
        CityConfig cityConfig = new CityConfig.Builder().title("选择城市")//标题
                .titleTextSize(18)//标题文字大小
                .titleTextColor("#585858")//标题文字颜  色
                .titleBackgroundColor("#E9E9E9")//标题栏背景色
                .confirTextColor("#585858")//确认按钮文字颜色
                .confirmText("确认")//确认按钮文字
                .confirmTextSize(16)//确认按钮文字大小
                .cancelTextColor("#585858")//取消按钮文字颜色
                .cancelText("取消")//取消按钮文字
                .cancelTextSize(16)//取消按钮文字大小
                .setCityWheelType(CityConfig.WheelType.PRO_CITY_DIS)//显示类，只显示省份一级，显示省市两级还是显示省市区三级
                .showBackground(true)//是否显示半透明背景
                .visibleItemsCount(7)//显示item的数量
                .province("天津市")//默认显示的省份
                .city("天津市")//默认显示省份下面的城市
                .district("滨海新区")//默认显示省市下面的区县数据
                .provinceCyclic(true)//省份滚轮是否可以循环滚动
                .cityCyclic(true)//城市滚轮是否可以循环滚动
                .districtCyclic(true)//区县滚轮是否循环滚动
                //                .setCustomItemLayout(R.layout.item_city)//自定义item的布局
                //                .setCustomItemTextViewId(R.id.item_city_name_tv)//自定义item布局里面的textViewid
                .drawShadows(false)//滚轮不显示模糊效果
                .setLineColor("#03a9f4")//中间横线的颜色
                .setLineHeigh(5)//中间横线的高度
                .setShowGAT(true)//是否显示港澳台数据，默认不显示
                .build();

        //设置自定义的属性配置
        mPicker.setConfig(cityConfig);
        //监听选择点击事件及返回结果
        mPicker.setOnCityItemClickListener(new OnCityItemClickListener() {
            @Override
            public void onSelected(ProvinceBean province, CityBean city, DistrictBean district) {
                //省份
                if (province != null)
                    address = province.toString();
                //城市
                if (city != null)
                    if (!province.toString().equals(city.toString()))
                        address = address + "-" + city.toString();
                //地区
                if (district != null)
                    address += "-" + district.toString();

                if (!address.equals("")) {
                    binding.llAddr.setVisibility(View.VISIBLE);
                    binding.btAddress.setVisibility(View.GONE);
                    binding.etAddr.setText(address);
                    setSave();
//                } else {
//                    et_addr.setVisibility(View.GONE);
//                    bt_addr.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onCancel() {
                ToastUtils.showLongToast(UpdateUserInfoActivity.this, "已取消");
            }
        });
        //显示
        mPicker.showCityPicker();
    }

    public void UpdataHeadImage() {
        if (Utils.isFastClick()) return;
        Intent it = new Intent(UpdateUserInfoActivity.this, UpdateHeadIconActivity.class);
        startActivityForResult(it, REQUEST_PICK);
        overridePendingTransition(R.anim.fade, R.anim.hold);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_PICK://系统相机返回
                if (resultCode == RESULT_OK) {
                    if (!Utils.isEmpty(data.getData())) {
                        binding.ivHeadPortrait.setImageURI(data.getData());
                        pDialog = new SweetAlertDialog(this, SweetAlertDialog.SUCCESS_TYPE);
                        //        pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
                        pDialog.setTitleText("头像上传成功!");
                        pDialog.setConfirmButton("OK", new SweetAlertDialog.OnSweetClickListener() {
                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                sweetAlertDialog.dismiss();
                            }
                        });
                        //  pDialog.setCancelable(false);
                        pDialog.show();
                        myHandler.sendEmptyMessageDelayed(101, 600);
                    }
                }
                break;
        }
    }

    // 保存个人修改信息
    public void setSave() {
        if (UINetWork(NetworkUtils.isConnected(this)))//检查网络是否断开的 提示，决定是否访问服务器
        {
            String str_tag = "1";
            FormBody formBody = new FormBody.Builder()
                    .add("token", sn.getString("token", ""))
                    .add("id", UserInfoId)
                    .add("userId", userId)
                    .add("realName", realName)
                    .add("idNumber", idNumber)
                    .add("gender", gender)
                    .add("socialId", socialId)
                    .add("address", address)
//                    .add("headIcon",headIcon)
                    .add("marryInfo", marryInfo)
                    .add("historyInfo", historyInfo)
                    .add("operationInfo", operationInfo)
                    .add("allergyInfo", allergyInfo)
                    .add("familyInfo", familyInfo)
                    .add("tasteInfo", tasteInfo)
                    .build();
            sendPostNetwork(str_tag, formBody, myHandler, UrlUtils.addr_edit_message);
        }
    }

//    //改写返回键功能
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            finish();
//            return false;
//        }
//        return super.onKeyDown(keyCode, event);
//    }
//
//
//    protected void onStop() {
//        super.onStop();
//        if (this.isFinishing()) {
//            mPicker = null;
//            myHandler.removeCallbacksAndMessages(null);
//        }
//    }


}